package com.qk.interceptor;

import com.qk.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
@Slf4j
//@Component
public class TokenInterceptor implements HandlerInterceptor {
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求路径
        String path = request.getRequestURI();
        //判断是否登录请求
        if(path.contains("/login")){
            log.info("登录请求：{}",path);
            return true;
        }
        //获取请求头 token
        String jwt = request.getHeader("token");
        //判断token是否为存在
        if(jwt == null|| jwt.isEmpty()){
            log.info("请求头没有token");
            response.setStatus(401);
            return false;
        }
        //解析 token,如果解析报错，则返回401
        try{
            JwtUtils.parseToken(jwt);
        } catch (Exception e) {
            log.info("token解析错误");
            response.setStatus(401);
            return false;
        }
        //放行
        return true;
    }
}
